package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("regions")
public class RegionController {


    @Autowired
    private ServletContext sct;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    /**
     * 查询所有地区
     * @return
     */
    @GetMapping
    public Object getRegions(){
        List<Region> regions = regionService.selectAll();
        return regions;
    }
    @GetMapping("/{state}")
    public Object getRegionsByState(@PathVariable int state){
        // 查询所有推荐状态的地区
        List<Region> regions = regionService.getRegionByState(state);
        return regions;
    }
    @GetMapping(value="/{regionId}/strategies",produces = "text/html;charset=utf-8")
    public void getRegionsByRegionId(@PathVariable("regionId") Long regionId, HttpServletResponse response) throws Exception {

        //当季攻略推荐
        StrategyQueryObject qo1 = new StrategyQueryObject();
        qo1.setState(Strategy.STATE_PUSH);
        qo1.setRegionId(regionId);
        qo1.setPageSize(0);
        PageInfo commend = strategyService.query(qo1);

        // 全部地区推荐
        StrategyQueryObject qo2 = new StrategyQueryObject();
        qo2.setRegionId(regionId);
        qo2.setPageSize(6);

        PageInfo all = strategyService.query(qo2);
        // 模板 + 数据

        // 创建freemarker 配置对象
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
        cfg.setDefaultEncoding("UTF-8");
        // 定义模板的加载路径
        cfg.setDirectoryForTemplateLoading(new File(sct.getRealPath("/template")));
        // 获取模板
        Template template = cfg.getTemplate("pushStrategy.ftl");
        // 封装数据
        Map<String,Object> data = new HashMap<String,Object>();
        data.put("commends",commend);
        data.put("all",all);
        // 响应数据
         template.process(data,response.getWriter());
    }

    @GetMapping(value="/{regionId}/strategies",produces = "application/json;charset=utf-8")
    public Object getRegionsByRegionId(StrategyQueryObject qo){
        return strategyService.query(qo);
    }

}
